<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>{{name}}</h2>
      <button @click="handle">点击</button>
    </div>
  </body>
</html>
<script src="http://chst.vip:8081/vue.js"></script>
<script>
  // 点击某个按钮后，开始侦听数据变化
  const vm = new Vue({
    el: "#app",
    data: {
      arr: [1, 2, 3],
      name: "李元浩",
    },
    methods: {
      handle() {
        // 点击按钮开始侦听这个name属性
        // api的调用方式
        // vm.$watch(侦听的属性或者函数，回调函数，{deep?,immediate?})
        this.$watch(
          "name",
          (newVal, oldVal) => {
            console.log("newVal===" + newVal);
            console.log("oldVal===" + oldVal);
          },
          { immediate: true }
        );
      },
    },
    watch: {
      //侦听数组的时候不需要使用deep模式
      //立即回调watch函数
      arr: {
        handler(newVal) {
          console.log("newVal==" + newVal);
        },
        immediate: true, //立即回调当前的侦听函数
      },
    },
  });
</script>
